package com.tinyshardingjdbc.tinyshardingjdbc.shardingasync.tool;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
public class ExecutorPluginUtils {

    /**
     * 获取sql语句
     *
     * @param invocation
     * @return
     */
    public static String getSqlByInvocation(Invocation invocation) {
        final Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameterObject = args[1];
        BoundSql boundSql = ms.getBoundSql(parameterObject);
        return boundSql.getSql();
    }

    /**
     * 包装sql后，重置到invocation中
     *
     * @param invocation
     * @param sql
     * @throws SQLException
     */
    public static void resetSql2Invocation(Invocation invocation, String sql, BoundSql boundSql, MappedStatement statement) {
        final Object[] args = invocation.getArgs();
        MappedStatement newStatement = newMappedStatement(statement, new BoundSqlSqlSource(boundSql));
        MetaObject msObject = MetaObject.forObject(newStatement, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(), new DefaultReflectorFactory());
        msObject.setValue("sqlSource.boundSql.sql", sql);
        args[0] = newStatement;
    }


    private static MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder =
                new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
            StringBuilder keyProperties = new StringBuilder();
            for (String keyProperty : ms.getKeyProperties()) {
                keyProperties.append(keyProperty).append(",");
            }
            keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
            builder.keyProperty(keyProperties.toString());
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());
        return builder.build();
    }

    /**
     * 查找分页参数
     *
     * @param parameterObject 参数对象
     * @return 分页参数
     */
    @SuppressWarnings("all")
    public static String findParameter(Object parameterObject, BoundSql boundSql, String findKey) {
        List<ParameterMapping> ParameterList = boundSql.getParameterMappings();
        List<Object> parList = new ArrayList<>();
        Map<String, Object> parameterMap = (Map<String, Object>) parameterObject;
        for (ParameterMapping p : ParameterList) {
            String key[] = p.getProperty().split("\\.");
            JSONObject jsonObject = JSON.parseObject(JSONObject.toJSONString(parameterMap.get(key[0])));
            if (jsonObject.containsKey(findKey)) {
                return jsonObject.getString(findKey);
            }
        }
        return null;
    }

    public static String dosql(String sql, List<Object> par) {
        StringBuffer stringBuffer = new StringBuffer();
        int j = 0;
        for (int i = 0; i < sql.length(); i++) {
            if (sql.charAt(i) == '?') {
                Object o = par.get(j);
                j++;
                if (o instanceof String) {
                    String newPar = "'" + o + "'";
                    stringBuffer.append(newPar);
                } else {
                    stringBuffer.append(o);
                }
            } else {
                stringBuffer.append(sql.charAt(i));
            }

        }
        System.out.println(stringBuffer.toString());
        return stringBuffer.toString();
    }

    public static Map<String, Object> parsePar(Object parameter, List<ParameterMapping> parameterList) {

        if (parameter instanceof Map) {
            return (Map<String, Object>) parameter;
        }
        Map<String, Object> parMap = new HashMap<>();
        if (parameter instanceof String || parameter instanceof
                Integer || parameter instanceof Long || parameter instanceof BigDecimal) {
            String str[] = parameter.toString().split(",");
            int i = 0;
            for (String s : str) {
                String key = JSONObject.parseObject(JSONObject.toJSONString(parameterList.get(i))).getString("property");
                parMap.put(key, s);
            }
        } else {
            parMap = JSON.parseObject(JSONObject.toJSONString(parameter), Map.class);
        }
        return parMap;
    }

    //    定义一个内部辅助类，作用是包装sq
    static class BoundSqlSqlSource implements SqlSource {
        private BoundSql boundSql;

        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }

        @Override
        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }

}
